//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package admin_user_api_serv

import (
	"context"
	"strings"

	"atomgit.com/openlinksaas/api-server/admin_api_serv/admin_common"
	"atomgit.com/openlinksaas/api-server/api_common"
	"atomgit.com/openlinksaas/api-server/config"
	"atomgit.com/openlinksaas/api-server/dao"
	"atomgit.com/openlinksaas/api-server/dao/user_dao"
	"atomgit.com/openlinksaas/proto-gen-go.git/user_api"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/mongo"
)

type UserAdminApiImpl struct {
	user_api.UnimplementedUserAdminApiServer
	adminCfg *config.AdminCfg
}

func NewUserAdminApiImpl(adminCfg *config.AdminCfg) *UserAdminApiImpl {
	return &UserAdminApiImpl{adminCfg: adminCfg}
}

func (apiImpl *UserAdminApiImpl) List(ctx context.Context, req *user_api.AdminListRequest) (*user_api.AdminListResponse, error) {
	emptyList := []*user_api.UserInfo{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminListResponse{
			Code:         user_api.AdminListResponse_CODE_WRONG_SESSION,
			ErrMsg:       "会话不存在",
			UserInfoList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminListResponse{
			Code:         user_api.AdminListResponse_CODE_NOT_AUTH,
			ErrMsg:       "未授权会话",
			UserInfoList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Read {
		return &user_api.AdminListResponse{
			Code:         user_api.AdminListResponse_CODE_NO_PERMISSION,
			ErrMsg:       "没有权限",
			UserInfoList: emptyList,
		}, nil
	}

	count, err := user_dao.UserInfoDao.CountByAdminApi(ctx, req.FilterByKeyword, req.Keyword, req.FilterByUserState, uint32(req.UserState))
	if err != nil {
		return nil, err
	}
	userItemList, err := user_dao.UserInfoDao.ListByAdminApi(ctx, req.FilterByKeyword, req.Keyword, req.FilterByUserState, uint32(req.UserState),
		int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}

	infoList := []*user_api.UserInfo{}
	for _, userItem := range userItemList {
		infoList = append(infoList, userItem.ToUserInfo())
	}

	return &user_api.AdminListResponse{
		Code:         user_api.AdminListResponse_CODE_OK,
		TotalCount:   count,
		UserInfoList: infoList,
	}, nil
}

func (apiImpl *UserAdminApiImpl) ListById(ctx context.Context, req *user_api.AdminListByIdRequest) (*user_api.AdminListByIdResponse, error) {
	emptyList := []*user_api.UserInfo{}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminListByIdResponse{
			Code:         user_api.AdminListByIdResponse_CODE_WRONG_SESSION,
			ErrMsg:       "会话不存在",
			UserInfoList: emptyList,
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminListByIdResponse{
			Code:         user_api.AdminListByIdResponse_CODE_NOT_AUTH,
			ErrMsg:       "未授权会话",
			UserInfoList: emptyList,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Read {
		return &user_api.AdminListByIdResponse{
			Code:         user_api.AdminListByIdResponse_CODE_NO_PERMISSION,
			ErrMsg:       "没有权限",
			UserInfoList: emptyList,
		}, nil
	}

	userItemList, err := user_dao.UserInfoDao.ListById(ctx, req.UserIdList)
	if err != nil {
		return nil, err
	}

	infoList := []*user_api.UserInfo{}
	for _, userItem := range userItemList {
		infoList = append(infoList, userItem.ToUserInfo())
	}
	return &user_api.AdminListByIdResponse{
		Code:         user_api.AdminListByIdResponse_CODE_OK,
		UserInfoList: infoList,
	}, nil
}

func (apiImpl *UserAdminApiImpl) Exist(ctx context.Context, req *user_api.AdminExistRequest) (*user_api.AdminExistResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminExistResponse{
			Code:   user_api.AdminExistResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminExistResponse{
			Code:   user_api.AdminExistResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Read {
		return &user_api.AdminExistResponse{
			Code:   user_api.AdminExistResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := user_dao.UserInfoDao.ExistByName(ctx, req.UserName)
	if err != nil {
		return nil, err
	}
	return &user_api.AdminExistResponse{
		Code:  user_api.AdminExistResponse_CODE_OK,
		Exist: exist,
	}, nil
}

func (apiImpl *UserAdminApiImpl) Get(ctx context.Context, req *user_api.AdminGetRequest) (*user_api.AdminGetResponse, error) {
	emptyInfo := &user_api.UserInfo{
		BasicInfo: &user_api.BasicUserInfo{},
	}

	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminGetResponse{
			Code:     user_api.AdminGetResponse_CODE_WRONG_SESSION,
			ErrMsg:   "会话不存在",
			UserInfo: emptyInfo,
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminGetResponse{
			Code:     user_api.AdminGetResponse_CODE_NOT_AUTH,
			ErrMsg:   "未授权会话",
			UserInfo: emptyInfo,
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Read {
		return &user_api.AdminGetResponse{
			Code:     user_api.AdminGetResponse_CODE_NO_PERMISSION,
			ErrMsg:   "没有权限",
			UserInfo: emptyInfo,
		}, nil
	}

	userItem, err := user_dao.UserInfoDao.Get(ctx, req.UserId)
	if err != nil {
		return &user_api.AdminGetResponse{
			Code:     user_api.AdminGetResponse_CODE_NO_USER,
			ErrMsg:   "用户不存在",
			UserInfo: emptyInfo,
		}, nil
	}

	return &user_api.AdminGetResponse{
		Code:     user_api.AdminGetResponse_CODE_OK,
		UserInfo: userItem.ToUserInfo(),
	}, nil
}

func (apiImpl *UserAdminApiImpl) SetState(ctx context.Context, req *user_api.AdminSetStateRequest) (*user_api.AdminSetStateResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminSetStateResponse{
			Code:   user_api.AdminSetStateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminSetStateResponse{
			Code:   user_api.AdminSetStateResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.SetState {
		return &user_api.AdminSetStateResponse{
			Code:   user_api.AdminSetStateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := user_dao.UserInfoDao.ExistById(ctx, req.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &user_api.AdminSetStateResponse{
			Code:   user_api.AdminSetStateResponse_CODE_NO_USER,
			ErrMsg: "用户不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = user_dao.UserInfoDao.UpdateUserState(sessCtx, req.UserId, uint32(req.UserState))
		if err != nil {
			return nil, err
		}
		return &user_api.AdminSetStateResponse{
			Code: user_api.AdminSetStateResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*user_api.AdminSetStateResponse), nil
}

func (apiImpl *UserAdminApiImpl) SetTestAccount(ctx context.Context, req *user_api.AdminSetTestAccountRequest) (*user_api.AdminSetTestAccountResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminSetTestAccountResponse{
			Code:   user_api.AdminSetTestAccountResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminSetTestAccountResponse{
			Code:   user_api.AdminSetTestAccountResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.SetTestAccount {
		return &user_api.AdminSetTestAccountResponse{
			Code:   user_api.AdminSetTestAccountResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := user_dao.UserInfoDao.ExistById(ctx, req.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &user_api.AdminSetTestAccountResponse{
			Code:   user_api.AdminSetTestAccountResponse_CODE_NO_USER,
			ErrMsg: "用户不存在",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = user_dao.UserInfoDao.UpdateUserTestAccount(sessCtx, req.UserId, req.TestAccount)
		if err != nil {
			return nil, err
		}
		return &user_api.AdminSetTestAccountResponse{
			Code: user_api.AdminSetTestAccountResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*user_api.AdminSetTestAccountResponse), nil
}

func (apiImpl *UserAdminApiImpl) Create(ctx context.Context, req *user_api.AdminCreateRequest) (*user_api.AdminCreateResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.Create {
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := user_dao.UserInfoDao.ExistByName(ctx, req.UserName)
	if err != nil {
		return nil, err
	}
	if exist {
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_USER_EXIST,
			ErrMsg: "用户已经存在",
		}, nil
	}

	req.Password = strings.Trim(req.Password, " \t\r\n")

	if len(req.Password) < 6 {
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_PASSWD_TOO_SIMPLE,
			ErrMsg: "密码太简单",
		}, nil
	}

	userId := uuid.NewString()
	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = api_common.CreateUser(sessCtx, userId, req.UserName, req.BasicInfo.DisplayName, req.BasicInfo.LogoUri, req.Password, req.TestAccount, user_api.USER_TYPE_USER_TYPE_INTERNAL)
		if err != nil {
			return nil, err
		}
		return &user_api.AdminCreateResponse{
			Code:   user_api.AdminCreateResponse_CODE_OK,
			UserId: userId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*user_api.AdminCreateResponse), nil
}

func (apiImpl *UserAdminApiImpl) ResetPassword(ctx context.Context, req *user_api.AdminResetPasswordRequest) (*user_api.AdminResetPasswordResponse, error) {
	sess, ok := dao.CacheDao.GetAdminSession(ctx, req.AdminSessionId)
	if !ok {
		return &user_api.AdminResetPasswordResponse{
			Code:   user_api.AdminResetPasswordResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	if !sess.AuthOk {
		return &user_api.AdminResetPasswordResponse{
			Code:   user_api.AdminResetPasswordResponse_CODE_NOT_AUTH,
			ErrMsg: "未授权会话",
		}, nil
	}
	adminUserCfg, err := admin_common.GetAdminUserConfig(ctx, apiImpl.adminCfg, sess.UserName)
	if err != nil {
		return nil, err
	}
	if !adminUserCfg.PermInfo.UserPerm.ResetPassword {
		return &user_api.AdminResetPasswordResponse{
			Code:   user_api.AdminResetPasswordResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	exist, err := user_dao.UserInfoDao.ExistById(ctx, req.UserId)
	if err != nil {
		return nil, err
	}
	if !exist {
		return &user_api.AdminResetPasswordResponse{
			Code:   user_api.AdminResetPasswordResponse_CODE_NO_USER,
			ErrMsg: "用户不存在",
		}, nil
	}

	req.Password = strings.Trim(req.Password, " \t\r\n")
	if len(req.Password) < 6 {
		return &user_api.AdminResetPasswordResponse{
			Code:   user_api.AdminResetPasswordResponse_CODE_PASSWD_TOO_SIMPLE,
			ErrMsg: "密码太简单",
		}, nil
	}

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx mongo.SessionContext) (interface{}, error) {
		err = user_dao.UserPasswdDao.Set(sessCtx, req.UserId, req.Password)
		if err != nil {
			return nil, err
		}
		return &user_api.AdminResetPasswordResponse{
			Code: user_api.AdminResetPasswordResponse_CODE_OK,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*user_api.AdminResetPasswordResponse), nil
}
